package com.jcfk.system.service;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jcfk.common.core.constant.Constants;
import com.jcfk.common.security.utils.SecurityUtils;
import com.jcfk.common.websocket.model.SocketMessage;
import com.jcfk.system.domain.dto.SysOrganizationDTO;
import com.jcfk.system.domain.model.SendMsgModel;
import com.jcfk.system.domain.po.*;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author awei 2024-01-12
 */
@Component
public class OaKeyworkRemindXxlJob {

    @Autowired
    private OaRemindPlanService oaRemindPlanService;

    @Autowired
    private OaKeyworkRemindService oaKeyworkRemindService;

    @Autowired
    private OaRemindUserService oaRemindUserService;


    @Autowired
    private OaKeyworkDailyService oaKeyworkDailyService;


    @Autowired
    private OaKeyworkWeeklyService oaKeyworkWeeklyService;

    /**
     * 多级分类服务
     */
    @Autowired
    private RefUserOrganizationMappingService refUserOrganizationMappingService;

    @Autowired
    private SysInternalMessageService sysInternalMessageService;

    @Autowired
    private WebSocketMessageService webSocketMessageService;

    @Autowired
    private SysBusinessGroupUserService sysBusinessGroupUserService;

    @Autowired
    private SysOrganizationService sysOrganizationService;

    private static Logger logger = LoggerFactory.getLogger(OaKeyworkRemindXxlJob.class);

    /**
     * 定时发送内容提示
     */
    @XxlJob("OaKeyworkRemindXxlJob")
    public void OaKeyworkRemindXxlJob() {
        // 获取周报日报提醒时间
        QueryWrapper<OaRemindPlan> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("create_time").last("LIMIT 1");
        OaRemindPlan item = oaRemindPlanService.getOne(queryWrapper);

        // 创建时间格式化器
        SimpleDateFormat df = new SimpleDateFormat("HH:mm");

        Date date = new Date();

        // 使用SimpleDateFormat对象格式化时间
        String formattedTime = df.format(date);

        // 获取今天的日期
        LocalDate today = LocalDate.now();
        // 获取星期几的数字表示
        DayOfWeek dayOfWeek = today.getDayOfWeek();
        int dayOfWeekValue = dayOfWeek.getValue();
        int year = today.getYear();

        Calendar calendar = Calendar.getInstance();
        int nowwewk = calendar.get(Calendar.WEEK_OF_YEAR);

        // 创建一个SimpleDateFormat对象，指定日期格式为yyyy-MM-dd
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String formattedDate = sdf.format(date);

        // 发送日报
        // if (true) {
        if (item != null && item.getDailyTime() != null && formattedTime.equals(item.getDailyTime())) {
            List<String> userIds = getUserIds(item, "1");

            QueryWrapper<OaKeyworkDaily> oaKeyworkDailyQueryWrapper = new QueryWrapper<>();
            oaKeyworkDailyQueryWrapper.lambda().eq(OaKeyworkDaily::getWorkDay, formattedDate);
            oaKeyworkDailyQueryWrapper.lambda().eq(OaKeyworkDaily::getDeleted, 0);
            List<OaKeyworkDaily> oaKeyworkDailies = oaKeyworkDailyService.list(oaKeyworkDailyQueryWrapper);
            List<String> IsComituserIds = oaKeyworkDailies.stream().map(OaKeyworkDaily::getCreatedUserId).collect(Collectors.toList());

            userIds.removeAll(IsComituserIds);

            if (userIds.size() > 0) {
                sendremindMessage(userIds, "您需要填写[ " + formattedDate + " ]的日报", "2");
            }
        }

        // 发送周报
        // if (true) {
        if (item.getWeekNum() != null && item.getWeekNum().equals(String.valueOf(dayOfWeekValue)) && item.getWeekTime().equals(formattedTime)) {
            // 查询没提交日报的人
            List<String> userIds = getUserIds(item, "2");

            QueryWrapper<OaKeyworkWeekly> oaKeyworkDailyQueryWrapper = new QueryWrapper<>();
            oaKeyworkDailyQueryWrapper.lambda().eq(OaKeyworkWeekly::getWorkYear, year);
            oaKeyworkDailyQueryWrapper.lambda().eq(OaKeyworkWeekly::getWorkWeek, nowwewk);
            oaKeyworkDailyQueryWrapper.lambda().eq(OaKeyworkWeekly::getDeleted, 0);
            List<OaKeyworkWeekly> oaKeyworkDailies = oaKeyworkWeeklyService.list(oaKeyworkDailyQueryWrapper);
            List<String> IsComituserIds = oaKeyworkDailies.stream().map(OaKeyworkWeekly::getCreatedUserId).collect(Collectors.toList());

            userIds.removeAll(IsComituserIds);

            if (userIds.size() > 0) {
                // 创建提醒
                sendremindMessage(userIds, "您需要填写[ " + year + "年第" + nowwewk + "周 ]的周报", "3");
            }
        }


    }

    /**
     * 获取接收人
     */
    private List<String> getUserIds(OaRemindPlan item, String type) {
        // 查询没提交日报的人
        QueryWrapper<OaRemindUser> remindUserQueryWrapper = new QueryWrapper<>();
        remindUserQueryWrapper.lambda().eq(OaRemindUser::getRemindId, item.getId());
        remindUserQueryWrapper.lambda().eq(OaRemindUser::getType, type);
        List<OaRemindUser> oaRemindUsers = oaRemindUserService.list(remindUserQueryWrapper);

        // 用户id
        List<String> userIds = new ArrayList<>();
        List<String> groupId = new ArrayList<>();
        String organizationId = "";

        for (OaRemindUser user : oaRemindUsers) {
            if (!StringUtils.isEmpty(user.getOrganizationId())) {
                organizationId = user.getOrganizationId();
            }
            if ("1".equals(user.getRemindType())) userIds.add(user.getUserId());
            if ("2".equals(user.getRemindType())) groupId.add(user.getGroupId());
        }


        // 根据组织 赋值接收人id
        if (!StringUtils.isEmpty(organizationId)) {
            SysOrganizationDTO sysOrganizationDTO = sysOrganizationService.get(organizationId);
            if (sysOrganizationDTO != null) {
                QueryWrapper<SysOrganization> sysOrganizationQueryWrapper = new QueryWrapper<>();
                sysOrganizationQueryWrapper.lambda().likeRight(SysOrganization::getAllId, sysOrganizationDTO.getAllId());
                List<SysOrganization> sysOrganizationList = sysOrganizationService.list(sysOrganizationQueryWrapper);

                List<String> organIds = sysOrganizationList.stream().map(SysOrganization::getId).collect(Collectors.toList());

                if (organIds.size() > 0) {
                    QueryWrapper<RefUserOrganizationMapping> refUserOrganizationMappingQueryWrapper = new QueryWrapper<>();
                    refUserOrganizationMappingQueryWrapper.lambda().in(RefUserOrganizationMapping::getOrganizationId, organIds);
                    List<String> ids = refUserOrganizationMappingService.list(refUserOrganizationMappingQueryWrapper).stream().map(RefUserOrganizationMapping::getUserId).collect(Collectors.toList());
                    userIds.addAll(ids);
                }

            }
        }


        // 根据组织 赋值接收人id
        if (groupId == null || groupId.size() > 0) {
            QueryWrapper<SysBusinessGroupUser> sysBusinessGroupUserQueryWrapper = new QueryWrapper<>();
            sysBusinessGroupUserQueryWrapper.lambda().in(SysBusinessGroupUser::getBusinessId, groupId).eq(SysBusinessGroupUser::getDeleted, 0);
            List<String> ids = sysBusinessGroupUserService.list(sysBusinessGroupUserQueryWrapper).stream().map(SysBusinessGroupUser::getUserId).collect(Collectors.toList());
            userIds.addAll(ids);
        }

        // 接收人去重
        userIds = userIds.stream().distinct().collect(Collectors.toList());

        return userIds;
    }

    /**
     * 发送
     */
    private void sendremindMessage(List<String> userIds, String concents, String type) {

        List<OaKeyworkRemind> reminds = new ArrayList<>();

        // 提示入库
        for (String userId : userIds) {
            OaKeyworkRemind oaKeyworkRemind = new OaKeyworkRemind();
            oaKeyworkRemind.setRemindType(type);
            oaKeyworkRemind.setReceiveUserId(userId);
            oaKeyworkRemind.setRemindContent(concents);
            oaKeyworkRemindService.setDefaultValue(oaKeyworkRemind);
            reminds.add(oaKeyworkRemind);
        }

        // 发送消息
        if (reminds.size() > 0) oaKeyworkRemindService.saveBigBatch(reminds);
        String tiile = type.equals("2") ? "日报小助手" : "周报小助手";
        sendMessage(reminds, tiile);
    }


    // 发送消息
    public List<SysInternalMessage> sendMessage(List<OaKeyworkRemind> reminds, String tille) {

        List<SysInternalMessage> list = new ArrayList<>();

        // 接受消息入库
        for (OaKeyworkRemind remind : reminds) {
            SysInternalMessage message = new SysInternalMessage();
            message.setTitle(tille);
            message.setUrl("/workbench/sysmessage");
            message.setMsgBody(remind.getRemindContent());
            message.setSendTime(new Date());
            message.setRecevieUserId(remind.getReceiveUserId());
            message.setReaded(Constants.NO);
            message.setEnabled(Constants.YES);
            message.setSendTime(new Date());
            message.setSendUserId("1");
            message.setCreatedUserId("1");
            message.setCreatedUserName("系统发送");
            message.setCreateTime(new Date());
            list.add(message);
        }

        // 入库
        if (list.size() > 0) sysInternalMessageService.saveBigBatch(list);

        for (SysInternalMessage internalMessage : list) {
            SocketMessage socketMessage = new SocketMessage();
            socketMessage.setMessageType("internalMessage");
            socketMessage.setUrl(internalMessage.getUrl());
            socketMessage.setMsgId(internalMessage.getId());
            socketMessage.setMessageContent(internalMessage.getTitle());
            socketMessage.setMessageLevel("INFO");
            webSocketMessageService.sendMessage(internalMessage.getRecevieUserId(), socketMessage);
        }

        return list;
    }

}
